package com.lft11.deadlock;

/**
 * Function: 		A {@code DeadLock} 死锁：多个线程互相抱着对方需要的资源，然后形成僵持。<br/>
 * Reason:   		ADD REASON.<br/>
 * Date:            2021-01-28 12:16<br/>
 * <p>
 * Class Name:      DeadLock<br/>
 * Package Name:    com.lft11.deadlock<br/>
 * @author Laifengting / E-mail:laifengting@foxmail.com
 * @version 1.0.0
 * @since JDK 8
 */
public class DeadLock {
	public static void main(String[] args) {
		Makeup g1 = new Makeup(0, "灰姑凉");
		Makeup g2 = new Makeup(1, "白雪公主");
		
		g1.start();
		g2.start();
	}
}

/**
 * 口红
 */
class Lipstick {

}

/**
 * 镜子
 */
class Mirror {

}

/**
 * 化妆
 */
class Makeup extends Thread {
	
	/**
	 * 需要的资源只有一份，用static 来保证只有一份。
	 */
	private static Lipstick lipstick = new Lipstick();
	private static Mirror mirror = new Mirror();
	
	/**
	 * 选择
	 */
	int choice;
	/**
	 * 使用化妆品的人。
	 */
	String girlName;
	
	Makeup(int choice, String girlName) {
		this.choice = choice;
		this.girlName = girlName;
		
	}
	
	@Override
	public void run() {
		// 化妆
		makeup();
	}
	
	/**
	 * 化妆的方法,互相持有对方的锁。
	 */
	private void makeup() {
		if (choice == 0) {
			// 去持有口红的锁
			synchronized (lipstick) {
				System.out.println(this.getName() + " 获得口红的锁");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				// 1秒后再去持有镜子的锁
				synchronized (mirror) {
					System.out.println(this.getName() + " 获得镜子的锁");
				}
			}
			
		} else {
			// 去持有镜子的锁
			synchronized (mirror) {
				System.out.println(this.getName() + " 获得镜子的锁");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				// 2秒后再去持有口红的锁
				synchronized (lipstick) {
					System.out.println(this.getName() + " 获得口红的锁");
				}
			}
		}
	}
	
}
